//
//  BGComposeView.swift
//  WeiboSwift
//
//  Created by 战场原黑仪 on 16/7/29.
//  Copyright © 2016年 战场原黑仪. All rights reserved.
//

import UIKit
import pop

class BGComposeView: UIView {

    // 代表记录mainVc
    var target: UIViewController?
    
    // 保存compose 数组
    private lazy var composeButtonInfos: [BGComposeModel] = [BGComposeModel]()
    
    // 保存按钮数组
    private lazy var buttons: [BGComposeButton] = [BGComposeButton]()
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREEN_W, height: SCREEN_H))
        setupUI()
        setupLayout()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 添加composeView
    func composeViewShow(target: UIViewController){
        // 赋值
        self.target = target
        // 添加view
        target.view.addSubview(self)
        
        setupButtonsAnim(true)
    }
    
    // 点击屏幕 view消失
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        setupButtonsAnim(false)
        // 延迟删除当前view
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
        
    }
    
    //MARK: - 设置视图
    private func setupUI() {
        addSubview(bgImageView)
        addSubview(logoImageView)
        addChildButtons()
    }
    
    private func setupLayout() {
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        logoImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
    }
    
    //MARK: - 懒加载
    //获取模糊界面
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    // logo
    private lazy var logoImageView: UIImageView = UIImageView(imageName: "compose_slogan")

}

//MARK: - 设置按钮
extension BGComposeView {
    //创建按钮
    private func addChildButtons() {
        self.composeButtonInfos = self.getComposeButtonInfos()
        
        // 按钮的宽和高
        let childW: CGFloat = 80
        let childH: CGFloat = 110
        // 按钮间距
        let childMargin: CGFloat = (SCREEN_W - childW*3)/4
        
        for (i,value)in composeButtonInfos.enumerate() {
            // 得到行数和列数
            let col = CGFloat(i%3)
            let row = CGFloat(i/3)
            
            // 创建button
            let button = BGComposeButton()
            // button的属性赋值
            button.composeButtonInfo = value
            // 给button添加点击事件
            button.addTarget(self, action: #selector(buttonClick), forControlEvents: UIControlEvents.TouchUpInside)
            button.setImage(UIImage(named: value.icon ?? ""), forState: UIControlState.Normal)
            button.setTitle(value.title, forState: UIControlState.Normal)
            button.frame = CGRect(x: childMargin + (childW+childMargin)*col, y: (childH+childMargin)*row+SCREEN_H, width: childW, height: childH)
            addSubview(button)
            // 保存按钮
            buttons.append(button)
        
        }
    }
    
    
    // 设置button动画 (isUp==true 代表向上 显示按钮  false 代表 消失按钮)
    private func setupButtonsAnim(isUp: Bool) {
        // 动画移动距离
        let margin: CGFloat = isUp ? -350 : 350
        
        //数组集合 
        let set = isUp ? self.buttons.enumerate() : self.buttons.reverse().enumerate()
        
        for (i, value) in set {
            // 设置动画
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 设置tovalue
            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
            //开始时间
            anim.beginTime = CACurrentMediaTime() + Double(i)*0.025
            //弹性系数
            anim.springBounciness = 10
            //动画速度
            anim.springSpeed = 8
            //添加动画
            value.pop_addAnimation(anim, forKey: nil)
        }
        
        
    }
    
    // MARK: - 监听方法
    @objc private func buttonClick(button: BGComposeButton) {
        //设置动画
        UIView.animateWithDuration(0.25, animations: { 
            //选中的按钮放大,其他缩小
            //遍历当前所有的按钮,判断是否是选中按钮
            for value in self.buttons {
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else {
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
                value.alpha = 0.3
            }
            
            }) { (_) in
                //动画结束时,跳转到对应的控制器
                UIView.animateWithDuration(0.25, animations: { 
                    // 遍历保存按钮数组还原状态
                    for value in self.buttons {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                        
                    }
                    }, completion: { (_) in
                        
                        //判断按钮模型下是否有对应控制器名称
                        guard let vcName = button.composeButtonInfo?.nextvc  else{
                            return
                        }
                        //获取项目名
                        guard let projectName = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
                            return
                        }
                        //创建对应控制器类,判断是否是UIViewController
                        guard let clazz = NSClassFromString("\(projectName).\(vcName)") as? UIViewController.Type else {
                            return
                        }
                        
                        //初始化控制器
                        let viewController = clazz.init()
                        
                        let navC = UINavigationController(rootViewController: viewController)
                        
                        self.target?.presentViewController(navC, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                        
                })
        }
    }

}

//MARK: - 获取按钮数据
extension BGComposeView {
    private func getComposeButtonInfos() -> [BGComposeModel] {
        // 获取路径
        let file = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        // plist文件转数组
        let array = NSArray(contentsOfFile: file)!
        // 创建一个可变的临时数组
        var tempArray:[BGComposeModel] = [BGComposeModel]()
        
        // 遍历array 字典转模型
        for dic in array {
            // 创建模型
            let composeButtonInfo = BGComposeModel(dict: dic as! [String: AnyObject])
            // 添加模型
            tempArray.append(composeButtonInfo)
        }
        return tempArray
    }
    
    
}
